//
//  PlayViewController.m
//  musicPlayer
//
//  Created by 鹏飞罗 on 16/8/20.
//  Copyright © 2016年 罗鹏飞. All rights reserved.
//

#import "PlayViewController.h"

@interface PlayViewController ()
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *lastButton;
@property (nonatomic, copy) void (^play) (UIButton *play);
@property (nonatomic, copy) void (^pause) (UIButton *psuse);
@end

@implementation PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createImageView];
    // Do any additional setup after loading the view from its nib.
    NSString *musicString = [[NSBundle mainBundle] pathForResource:@"周杰伦 - 稻香" ofType:@"mp3"];
    
    
    NSURL *musicURL = [NSURL fileURLWithPath:musicString];
    
    AVPlayerItem *musicItem = [[AVPlayerItem alloc] initWithURL:musicURL];
    self.player = [[AVPlayer alloc] initWithPlayerItem:musicItem];
    [self.player play];
    [self.playButton addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.playSlider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];

//    _totalTime = CMTimeGetSeconds(self.player.currentItem.asset.duration);
//    self.playSlider.minimumValue = 0;
//    self.playSlider.maximumValue = _totalTime;
    
    
//    self.playSlider.value = CMTimeGetSeconds(self.player.currentItem.currentTime);
    [self addVideoKVO];
    
}
- (void) createImageView {
    self.imageView.image = [UIImage imageNamed:@"jielun"];
    self.imageBackgroundView.layer.cornerRadius = self.imageBackgroundView.frame.size.width / 4 ;
    self.imageBackgroundView.clipsToBounds = YES;
    [self initAnimatiom];
}
- (void)initAnimatiom {
    //创建一个绕z轴选择的动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转一周
    animation.toValue = @(2*M_PI);
    //循环次数，尽量大
    animation.repeatCount = MAXFLOAT;
    //执行一次动画需要的时间
    animation.duration = 50.0f;
    [self.imageView.layer addAnimation:animation forKey:@"rotationAnimation"];
}

- (void) valueChange:(UISlider *)slider {

    CMTime currentTime = CMTimeMake(slider.value, 1);

    [self.player pause];
    [self.player seekToTime:currentTime completionHandler:^(BOOL finished) {
       [self.player play];
    }];
    
}
#pragma mark - KVO
- (void)addVideoKVO {

    //KVO
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
}
- (void) removeVideoKVO {
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    AVPlayerItem *item = object;
    if ([keyPath isEqualToString:@"status"]) {
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            __weak typeof(UISlider *) weakSlider = _playSlider;
            __weak typeof(UILabel *) weakLabel = _leftLabel;
            __weak typeof(UILabel *) weakRestLable = _rightLabel;
            CMTime allTime = item.duration;
            CGFloat allTimeSeconds = allTime.value / allTime.timescale;
            self.playSlider.minimumValue = 0;
            self.playSlider.maximumValue = allTimeSeconds;
            
    // 获取当前时间
            CMTime currentTime = item.currentTime;
            CGFloat currentTimeSeconds = currentTime.value / currentTime.timescale;
            self.playSlider.value = currentTimeSeconds;
            self.leftLabel.text =  [NSString stringWithFormat:@"%02d:%02d",(int)currentTimeSeconds/60,(int)currentTimeSeconds%60];
            self.rightLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)allTimeSeconds/60,(int)allTimeSeconds%60];
//            添加定时器
            [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                
                weakSlider.value = time.value / time.timescale;
                // 当前秒数
                CGFloat time1 = time.value / time.timescale;
                weakLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)time1/60,(int)time1%60];
               //剩余秒数
                CGFloat time2 = allTimeSeconds - time1;
                weakRestLable.text = [NSString stringWithFormat:@"%02d:%02d",(int)time2/60,(int)time2%60];
            }];
        }
    }
}


- (void)play:(void (^)(UIButton *))play pause:(void (^)(UIButton *))pause {
    self.play = play;
    self.pause = pause;
}

- (void)play:(UIButton *)play {
    [self.player play];
    [play setImage:[UIImage imageNamed:@"hp_player_btn_pause_normal"] forState:UIControlStateNormal];
    [play removeTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    [play addTarget:self action:@selector(pause:) forControlEvents:UIControlEventTouchUpInside];
    self.play(play);
    
}
- (void)pause:(UIButton *)pause {
    
    [self.player pause];
    [pause setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    [pause removeTarget:self action:@selector(pause:) forControlEvents:UIControlEventTouchUpInside];
    [pause addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    self.pause(pause);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
